package com.adtech.farmProducts.activities.activity;

import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.adtech.farmProducts.base.BaseNfcActivity;
import com.google.gson.reflect.TypeToken;
import com.adtech.common.Common;
import com.adtech.common.http.AsyncHttpPostFormData;
import com.adtech.common.http.AsyncHttpResponse;
import com.adtech.common.http.AsyncOkHttpClient;
import com.adtech.common.http.AsyncResponseHandler;
import com.adtech.common.model.RspModel;
import com.adtech.common.utils.MobileUtil;
import com.adtech.common.utils.SPUtil;
import com.adtech.farmProducts.App;
import com.adtech.farmProducts.R;
import com.adtech.farmProducts.base.BaseActivity;
import com.adtech.farmProducts.widget.ClearTextIconEditText;

import java.io.IOException;
import java.lang.reflect.Type;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author:  xiaocz.
 * Descr:   忘记密码
 */
public class ForgetPwdActivity extends BaseNfcActivity implements View.OnClickListener {


    /**
     * UI
     */
    @BindView(R.id.root_layout)
    LinearLayout rootLayout;
    @BindView(R.id.ed_name)
    ClearTextIconEditText mPhoneView;
    @BindView(R.id.code)
    ClearTextIconEditText mCodeView;
    @BindView(R.id.get_code)
    TextView mGetCodeView;
    @BindView(R.id.ed_pwd)
    ClearTextIconEditText edPwd;
    @BindView(R.id.ed_confirm_pwd)
    ClearTextIconEditText edConfirmPwd;

    // 创建短信倒计时计数器的对象
    private SmsCodeCountDownTimer mSmsCodeCountDownTimer;

    /**
     * 显示注册界面
     */
    public static void show(Context context) {
        Intent intent = new Intent(context, ForgetPwdActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_forget;
    }

    @Override
    protected void initWidgets() {
        super.initWidgets();
    }

    @OnClick({R.id.get_code, R.id.btn_forget})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.get_code:
                String phone = String.valueOf(mPhoneView.getText());
                // 校验数据
                if (!MobileUtil.checkMobile(phone)) {
                    App.getInstance().showMessage("请输入正确的手机号！");
                    return;
                } else {
                    getCode(phone);
                }
                break;
            case R.id.btn_forget:
                String mobile = String.valueOf(mPhoneView.getText()).trim();
                // 校验数据
                if (!MobileUtil.checkMobile(mobile)) {
                    App.getInstance().showMessage("请输入正确的手机号！");
                    return;
                }
                String code = String.valueOf(mCodeView.getText()).trim();
                if ("".equals(code) || code.length() < 6) {
                    App.getInstance().showMessage("请输入正确的验证码！");
                    return;
                }
                String pwd = String.valueOf(edPwd.getText()).trim();
                String confirmPwd = String.valueOf(edConfirmPwd.getText()).trim();
                if ("".equals(pwd) || pwd.length() < 6) {
                    App.getInstance().showMessage("密码长度必须大于六位数！");
                    return;
                }
                if (!pwd.equals(confirmPwd)) {
                    App.getInstance().showMessage("两次密码输入不相同！");
                    return;
                }
                onRegister(mobile, code, confirmPwd);
                break;
        }
    }

    /**
     * 发送验证码
     */
    private void getCode(String phone) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("phone", phone);
        okHttpClient.post(Common.Constant.API_IP + "api/Driver/driverUpdatePwdVerificationCode", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                e.printStackTrace();
                onDismiss();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, "发送验证码");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.isStatus()) {
                            // 初始化短信倒计时计算器（90秒）
                            mSmsCodeCountDownTimer = new SmsCodeCountDownTimer(90000, 1000);
                            // 启动短信计时器
                            mSmsCodeCountDownTimer.start();
                        }
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 重置密码
     */
    private void onRegister(final String mobile, String code, String pwd) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("phone", mobile);
        asyncHttpPostFormData.addFormData("yanzhengma", code);
        asyncHttpPostFormData.addFormData("pwd", pwd);
        okHttpClient.post(Common.Constant.API_IP + "api/Driver/driverUpdatePwd", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                e.printStackTrace();
                onDismiss();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, "注册");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.isStatus()) {
                            SPUtil.put(Common.Static.remember_pwd, true);
                            SPUtil.put(Common.Static.name_key, mobile);
                            finish();
                        }
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 实现短信验证码倒计时功能
     */
    public class SmsCodeCountDownTimer extends CountDownTimer {

        private SmsCodeCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mGetCodeView.setEnabled(false);
            // 短信验证码倒计时
            mGetCodeView.setText(String.valueOf("重新发送（" + millisUntilFinished / 1000L + "s)"));
            mGetCodeView.setTextColor(getResources().getColor(R.color.textColorAccent));
        }

        @Override
        public void onFinish() {
            mGetCodeView.setEnabled(true);
            mGetCodeView.setText("获取验证码");
            mGetCodeView.setTextColor(getResources().getColor(R.color.textColorFirst));
        }
    }

    @Override
    protected void onDestroy() {
        if(mSmsCodeCountDownTimer!=null){
            mSmsCodeCountDownTimer.cancel();
        }
        super.onDestroy();
    }
}
